<template>
    <van-button
        v-if="isFollowed"
        :loading="loading"
        class="follow-btn"
        round
        size="small"
        @click="onFollow"
    >已关注</van-button>

    <van-button
        v-else
        :loading="loading"
        class="follow-btn"
        type="info"
        color="#3296fa"
        round
        size="small"
        icon="plus"
        @click="onFollow"
    >关注</van-button>
</template>

<script>
import { addFollowAPI, deleteFollowAPI } from '../api/index.js'
export default {
//   model: {
//     prop: 'isFollowed',
//     event: 'update-follow'
//   },
  props: {
    isFollowed: {
      type: Boolean,
      default: false
    },
    // value: {
    //   type: Boolean,
    //   default: false
    // },
    userId: { // 用户id
      type: String,
      default: ''
    }
  },
  name: 'FollowUser',
  data () {
    return {
      loading: false
    }
  },
  methods: {
    async onFollow () {
      this.loading = true // 展示关注按钮的 loading 状态
      try {
        if (this.isFollowed) {
          // 已关注，取消关注
          await deleteFollowAPI(this.userId)
        } else {
          await addFollowAPI(this.userId)
        }
        // 更新视图
        // this.article.is_followed = !this.article.is_followed
        // this.$emit('update-follow', !this.isFollowed)
        this.$emit('update:isFollowed', !this.isFollowed)
        // this.$emit('update-is_followed', !this.value)
      } catch (error) {
        if (error.response && error.response.status === 400) {
          this.$toast('你不能关注你自己！')
        } else {
          this.$toast('操作失败')
        }
      }
      this.loading = false // 关闭关注按钮的 loading 状态
    }
  }
}
</script>

<style lang="less" scoped>

</style>
